<?php
/**
 * Created by PhpStorm.
 * User: lizx
 * Date: 2018/3/12
 * Time: 11:52
 */

namespace app\api\controller;

use app\api\service\ApplyShaohuoService;
use app\common\Model\ShaohuoProblem;
use app\common\Model\User;
use app\common\Model\UserShaohuo;
use app\common\Model\UserShaohuoFuncs;
use think\Controller;
use think\Db;
use think\exception\ErrorException;
use think\Request;

class Exam extends Controller
{

    //资料申请状态
    protected $_apply_status = array(
        0 => '去提交',
        1 => '审核中',
        2 => '审核成功',
        3 => '审核不通过',
    );

    protected $_exam_status;
    protected $_a_status;
    protected $_user_type;
    protected $_fail_reason;

    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        $this->init();
    }

    public function init(){
        $uid = $_GET['uid'] ?? $_POST['uid'];
        $userInfo = UserShaohuo::get(['uid' => $uid]);
        if (empty($userInfo)) {
            Db::startTrans();
            try{
                $userInfo = UserShaohuo::create(['uid' => $uid]);
                $user_shaohuo_funcs = new UserShaohuoFuncs();
                $user_shaohuo_funcs->saveAll([
                    ['uid' => $uid,'fc_id' => 1,'user_status' => 1],
                    ['uid' => $uid,'fc_id' => 2,'user_status' => 1],
                ]);
                Db::commit();
            }catch (ErrorException $exception){
                Db::rollback();
                echo json_encode([
                    'errcode' => 00000,
                    'errmsg' => '失败',
                    'data' => [
                    ]
                ]);die;
            }
        }
        $this->_user_type = $userInfo['status'] ?? 0;
//        $this->_user_type = 2;
//        if (($this->_user_type & 2) == 2) {
        if ($this->_user_type == 1) {
            //如果已经是捎货人
            $this->_a_status = 2;
            $this->_exam_status = array(
                1 => 1,
                2 => 1,
                3 => 1,
                4 => 1
            );
        } else {
            //查看用户的申请资料状态
//            $applyInfo = ExamModel::getInstance()->getShipperApplyInfo($uid);
            $applyInfo = UserShaohuo::get(['uid' => $uid]);
            $this->_a_status = $applyInfo->apply_status;
//            if (!empty($applyInfo)) {
//                $this->_a_status = $applyInfo['status'];
//            }
            $examStatusArr = array(
                1 => 0,
                2 => 0,
                3 => 0,
                4 => 0
            );
            //查看四节的状态
//            $statusArr = number2pos($applyInfo['exam_status']);
            $statusArr = $this->number2pos($userInfo['exam_status'] ?? 0);
            foreach ($statusArr as $key => $value) {
                $examStatusArr[$value] = 1;
            }
            $this->_exam_status = $examStatusArr;
            $this->_fail_reason = $userInfo['remark'] ?? '';
        }
    }

    /**
     * 十进制数字转换返回所有(特定)置位位置
     * @param $number
     * @param int $pos
     * @return array|int
     */
    function number2pos($number, $pos = 0)
    {
        if ($pos) {
            return ($number >> ($pos - 1)) & 1;
        }
        $result = array();
        $bin = decbin($number);
        $count = strlen($bin);
        for ($i = 1; $i <= $count; $i++) {
            if (($number >> ($i - 1)) & 1) {
                //if (!empty($pos) && !in_array($i, $pos)) continue;
                $result[] = $i;
            }
        }
        return $result;
    }


    /**
     * 根据置位位置数组转换成十进制
     * @param $pos int|array 置位位置(数组)
     * @param int $number 原始十进制
     * @return int 十进制数字,用于存到数据库
     * @example pos2number(array(1,2))=>3,pos2number(array(1,2),10)=>11
     */
    function pos2number($pos, $number = 0)
    {
        $posArray = is_array($pos) ? $pos : array($pos);
        $count = count($posArray);
        for ($i = 0; $i < $count; $i++) {
            $number |= (1 << (intval($posArray[$i]) - 1));
        }
        return $number;
    }

    //捎货人申请主页
    public function index() {
        $uid = $_GET['uid'];
//        $uid = intval($this->_request->getRequest('uid'));
//        $this->_a_status = 0;

        return $this->fetch('/exam/index',array(
            'uid' => $uid,
            'user_type' => $this->_user_type,
            'apply_status' => $this->_a_status,
            'apply_status_words' => $this->_apply_status[$this->_a_status],
            'exam_status' => $this->_exam_status
        ));
    }

    //审核失败提示页
    public function applyfail() {
        $uid = $_GET['uid'];
        return $this->fetch('/exam/applytip', array(
            'uid' => $uid,
            'apply_status' => $this->_a_status,
            'fail_reason' => $this->_fail_reason
        ));
    }

    //第一节学习
    public function chapter1() {
        $uid = $_GET['uid'];
        return $this->fetch('/exam/chapter1',array(
            'uid' => $uid,
            'exam_status' => $this->_exam_status
        ));
    }

    //第二节学习
    public function chapter2() {
        $uid = $_GET['uid'];
        return $this->fetch('/exam/chapter2', array('uid' => $uid,'exam_status' => $this->_exam_status));
    }

    //第三节学习
    public function chapter3() {
        $uid = $_GET['uid'];
        return $this->fetch('/exam/chapter3', array('uid' => $uid,'exam_status' => $this->_exam_status));
    }

    //第四节在线考试
    public function chapter4() {
        //随机10道单选，5道多选
        $uid = $_GET['uid'];

        $oneAnswerSql ="SELECT * FROM `sh_shaohuo_problem` WHERE type= 0 AND status=1 ORDER BY RAND() LIMIT 10";
        $res['oneRes'] = Db::query($oneAnswerSql);

        $multiAnswerSql ="SELECT * FROM `sh_shaohuo_problem` WHERE type= 1 AND status=1 ORDER BY RAND() LIMIT 10";
        $res['multiRes'] = Db::query($multiAnswerSql);

        $examItems = $res;

        return $this->fetch('/exam/chapter4',array(
            'examItems' => array_merge($examItems['oneRes'],$examItems['multiRes']),
            'uid' => $uid,
            'exam_status' => $this->_exam_status
        ));
    }

    //修改学习完成状态
    public function updateExamStatus() {
        $chapter = $_POST['chapter'];
        $uid = $_POST['uid'];

        //如果是老捎货用户
//        if (($this->_user_type & 2) != 2) {
        //如果未成为捎货用户
        if ($this->_user_type == 0) {
            //检验学习的顺序
            if (!$this->_checkChapterSequence($chapter)) {
                return Fun::error('');
//                return $this->output(funcReturn(Error::FAILED, array('errmsg' => '请完成前面章节的学习！')));
            }
            //完成该章节的学习
            ApplyShaohuoService::instance()->learnChapter($chapter,$uid);
//            ExamModel::getInstance()->learnChapter($chapter, $uid);
        }

        echo json_encode([

            'errcode' => 0,
            'errmsg' => '成功',
            'data' => [
                'next' => $chapter + 1
            ]
        ]);die;

        return Fun::success(['next' => $chapter + 1]);

        $this->output(funcReturn(Error::SUCCESS, array('next' => $chapter + 1)));
    }

    protected function _checkChapterSequence($chapter) {
        //校验学习章节的顺序状态
        for ($i=1; $i < $chapter; $i++) {
            if ($this->_exam_status[$i] == 0) {
                return false;
            }
        }
        return true;
    }

    /**
     * 检查习题，写入数据库
     * @items，以问题id位索引，答案是以逗号隔开的值的数组。
     * @uid ，用户id
     * return errItems arr 返回错误习题
     */
    public function check()
    {
        $items = $_POST['items'];
        $uid = $_POST['uid'];
        $itemIds = implode(',',array_keys($items));
        $allItems = ShaohuoProblem::where("sp_id in ({$itemIds})")->select();

        $errItems = array();

        foreach ($allItems as $key => $value) {
            //合成每一道题的最终答案如果跟答案不一致，则题目答错
            if ($this->pos2number($items[$value['sp_id']]) != $value['answer']) {
                array_push($errItems, $value);
            }
        }

        //没有错题，完成考试,并且修改用户类型为捎货人
        if (empty($errItems)) {

            UserShaohuo::where(['uid' => $uid])->update(['status' => 1]);
            UserShaohuoFuncs::where(['uid' => $uid])
                ->where('fc_id = 1 or fc_id = 2')
                ->update(['status' => 1]);
            //完成该章节的学习
            ApplyShaohuoService::instance()->learnChapter(4,$uid);

            echo json_encode([
                'errcode' => 0,
                'errmsg' => '成功',
            ]);die;
        } else {
            echo json_encode([

                'errcode' => 8041,
                'errmsg' => '成功',
                'data' => [
                    'err_item' => $errItems
                ]
            ]);die;
        }
    }
}